/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/idenger">idenger</a> All rights reserved.
 */
package com.idenger.modules.edu.web.selectiontitle;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.idenger.modules.edu.entity.common.BaseResponseMsg;
import com.idenger.modules.edu.entity.common.ResponseMsg;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.idenger.common.config.Global;
import com.idenger.common.persistence.Page;
import com.idenger.common.web.BaseController;
import com.idenger.common.utils.StringUtils;
import com.idenger.common.utils.excel.ExportExcel;
import com.idenger.common.utils.excel.ImportExcel;
import com.idenger.modules.edu.entity.questionwarehouse.EduQuestionWarehouse;
import com.idenger.modules.edu.entity.selectiontitle.EduSelectionTitle;
import com.idenger.modules.edu.service.questionwarehouse.EduQuestionWarehouseService;
import com.idenger.modules.edu.service.selectiontitle.EduSelectionTitleService;

/**
 * 选择题Controller
 * @author 兰正军
 * @version 2017-11-30
 */
@Controller
@RequestMapping(value = "${adminPath}/edu/selectiontitle/eduSelectionTitle")
public class EduSelectionTitleController extends BaseController {

	@Autowired
	private EduSelectionTitleService eduSelectionTitleService;
	@Autowired
	private EduQuestionWarehouseService eduQuestionWarehouseService;
	
	@ModelAttribute
	public EduSelectionTitle get(@RequestParam(required=false) String id) {
		EduSelectionTitle entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = eduSelectionTitleService.get(id);
		}
		if (entity == null){
			entity = new EduSelectionTitle();
		}
		return entity;
	}
	
	@RequiresPermissions("edu:selectiontitle:eduSelectionTitle:view")
	@RequestMapping(value = {"list", ""})
	public String list(EduSelectionTitle eduSelectionTitle, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<EduSelectionTitle> page = eduSelectionTitleService.findPage(new Page<EduSelectionTitle>(request, response), eduSelectionTitle); 
		model.addAttribute("page", page);
		return "modules/edu/selectiontitle/eduSelectionTitleList";
	}
	
	@RequestMapping(value = "pageByWarehouse")
	public String pageByWarehouse(EduSelectionTitle eduSelectionTitle,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		Page<EduSelectionTitle> page = eduSelectionTitleService.findListByWarehourseByPage(new Page<>(request, response), eduSelectionTitle);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData(page);
		return renderString(response, baseResponseMsg);
	}

	@RequestMapping(value = "deleteWarhourse")
	public String deleteWarhourse(EduQuestionWarehouse eduQuestionWarehouse,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		String ids = request.getParameter("ids");
		String[] idArray = ids.split(",");
		for(String id :idArray){
			EduQuestionWarehouse eduQuestionWarehouse2 = new EduQuestionWarehouse();
			eduQuestionWarehouse2.setId(id);
			eduQuestionWarehouseService.delete(eduQuestionWarehouse2);
		}
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData("删除成功");
		return renderString(response, baseResponseMsg);
	}
	

	@RequiresPermissions("edu:selectiontitle:eduSelectionTitle:view")
	@RequestMapping(value = "form")
	public String form(EduSelectionTitle eduSelectionTitle, Model model) {
		model.addAttribute("eduSelectionTitle", eduSelectionTitle);
		return "modules/edu/selectiontitle/eduSelectionTitleForm";
	}


	@RequestMapping(value = "save")
	public String save(EduSelectionTitle eduSelectionTitle,  HttpServletRequest request, HttpServletResponse response, Model model) {
		if (!beanValidator(model, eduSelectionTitle)){
			return form(eduSelectionTitle, model);
		}
		BaseResponseMsg baseResponseMsg;
		//判断其是否选为题库
		
		addQuestionWarhouse(eduSelectionTitle);
		eduSelectionTitleService.save(eduSelectionTitle);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData(eduSelectionTitle);
		return renderString(response, baseResponseMsg);
	}
	
	public void addQuestionWarhouse(EduSelectionTitle eduSelectionTitle){
		//判断该题目是否被选择为添加到题库
		if("1".equals(eduSelectionTitle.getIsCheckQuesionWarehouse())){
			EduSelectionTitle eduSelectionTitleWarehouse = new EduSelectionTitle();
			eduSelectionTitleWarehouse.setTitle(eduSelectionTitle.getTitle());
			eduSelectionTitleWarehouse.setTrueResult(eduSelectionTitle.getTrueResult());
			eduSelectionTitleWarehouse.setOp1(eduSelectionTitle.getOp1());
			eduSelectionTitleWarehouse.setOp2(eduSelectionTitle.getOp2());
			eduSelectionTitleWarehouse.setOp3(eduSelectionTitle.getOp3());
			eduSelectionTitleWarehouse.setOp4(eduSelectionTitle.getOp4());
			eduSelectionTitleWarehouse.setOp5(eduSelectionTitle.getOp5());
			eduSelectionTitleWarehouse.setOp6(eduSelectionTitle.getOp6());
			eduSelectionTitleWarehouse.setOp7(eduSelectionTitle.getOp7());
			eduSelectionTitleWarehouse.setType(eduSelectionTitle.getType());
			eduSelectionTitleService.save(eduSelectionTitleWarehouse);
			EduQuestionWarehouse eduQuestionWarehouse = new EduQuestionWarehouse();
			eduQuestionWarehouse.setSubjectId(eduSelectionTitleWarehouse.getId());
			eduQuestionWarehouseService.save(eduQuestionWarehouse);
		}
	}
	
	
	
	@RequiresPermissions("edu:selectiontitle:eduSelectionTitle:edit")
	@RequestMapping(value = "delete")
	public String delete(EduSelectionTitle eduSelectionTitle, RedirectAttributes redirectAttributes) {
		eduSelectionTitleService.delete(eduSelectionTitle);
		addMessage(redirectAttributes, "删除选择题成功");
		return "redirect:"+Global.getAdminPath()+"/edu/selectiontitle/eduSelectionTitle/?repage";
	}
	
	@RequestMapping(value = "ImportQuestionWarehouse")
	public String ImportQuestionWarehouse(MultipartFile file,RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		int successNum = 0;
		int failureNum = 0;
		try {
			ImportExcel ei = new ImportExcel(file,1,0);
			List<EduSelectionTitle> list = ei.getDataList(EduSelectionTitle.class);
				for(EduSelectionTitle eduSelectionTitle :list){
					if("单选题".equals(eduSelectionTitle.getTitle())){
						eduSelectionTitle.setTitle("1");
					}
					if("多选题".equals(eduSelectionTitle.getTitle())){
						eduSelectionTitle.setTitle("2");
					} 
					eduSelectionTitleService.save(eduSelectionTitle);
					EduQuestionWarehouse eduQuestionWarehouse = new EduQuestionWarehouse();
					eduQuestionWarehouse.setSubjectId(eduSelectionTitle.getId());
					eduQuestionWarehouseService.save(eduQuestionWarehouse);
					successNum++;
				}
			}catch(ConstraintViolationException ex){  
				logger.debug("错误"+ex.getMessage());
                failureNum++;  
            }catch (Exception ex) {  
                failureNum++;  
            	logger.debug("错误"+ex.getMessage());
            }  
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData(successNum);
		return renderString(response, baseResponseMsg);
	}
	@RequestMapping(value = "export")
	public String export(EduSelectionTitle eduSelectionTitle,RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response, Model model){
		try {
			List<EduSelectionTitle> list = eduSelectionTitleService.findList(eduSelectionTitle);
			String fileName = "题库导出模板"+new Date().getTime()+".xlsx";
			ExportExcel exportExcel = new ExportExcel("题库",  EduSelectionTitle.class);
			exportExcel.setDataList(list);
			exportExcel.write(response, fileName);
			exportExcel.dispose();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	@RequestMapping(value = "downloadTemplate")
	public String downloadTemplate(EduSelectionTitle eduSelectionTitle,RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response, Model model){
		try {
			downloadFile(request, response, "题库导入模板.xlsx");
			return null;
		} catch (FileNotFoundException e) {
			addMessage(redirectAttributes, "题库导入模板下载失败, 请求的文件不存在！失败信息：" + e.getMessage());
		} catch (Exception e) {
			addMessage(redirectAttributes, "题库导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/edu/user/eduUser/?repage";
	}
	
	 public void downloadFile(HttpServletRequest request, HttpServletResponse response, String fileName) 
				throws ServletException, IOException {
	        File file = new File(Global.getUserfilesBaseDir() + Global.TEMPLATE_FILES_BASE_URL + fileName);
			int fleng = (int) file.length();
			byte[] content = new byte[fleng];
			// 将文件读入内存
			FileInputStream in = new FileInputStream(file);
			in.read(content);
			in.close();
			// 设置响应类型为文件
			response.setContentType("application/octet-stream; charset=gb2312");
			response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("GBK"),"ISO8859_1"));
			response.setContentLength(content.length);
			// 写入文件内容
			response.getOutputStream().write(content);
			response.flushBuffer();
		}
	 
	@RequestMapping(value = "findSelectionTitle")
	 public String findSelectionTitle(EduSelectionTitle eduSelectionTitle, HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		 String ids = request.getParameter("ids");
		 String[] idArray = ids.split(",");
		 List<EduSelectionTitle> list = new ArrayList<>();
		 for(String id:idArray){
			 EduSelectionTitle selectionTitleForSave = eduSelectionTitleService.get(id);
			 if(selectionTitleForSave != null){
				 selectionTitleForSave.setId(null);
				 eduSelectionTitleService.save(selectionTitleForSave);
				 list.add(selectionTitleForSave);
			 }
		 }
		 baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData(list);
		return renderString(response, baseResponseMsg);
	 }
}